// Copyright 2009 Thiago H. de Paula Figueiredo
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package br.com.arsmachina.module.factory.impl;

import java.io.Serializable;
import java.util.List;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import br.com.arsmachina.controller.Controller;
import br.com.arsmachina.dao.DAO;
import br.com.arsmachina.dao.SortCriterion;
import br.com.arsmachina.module.factory.ControllerFactory;
import br.com.arsmachina.module.factory.impl.ControllerFactoryImpl;
import br.com.arsmachina.module.service.DAOSource;

/**
 * {@link ControllerFactory} that builds {@link SpringControllerImpl} subclasses.
 * 
 * @author Thiago H. de Paula Figueiredo
 */
public class SpringControllerFactory extends ControllerFactoryImpl {

	final private PlatformTransactionManager transactionManager;

	final private DAOSource daoSource;

	/**
	 * Single constructor of this class.
	 * 
	 * @param transactionManager a {@link PlatformTransactionManager}. It cannot be null.
	 * @param daoSource a {@link DAOSource}. It cannot be null.
	 */
	public SpringControllerFactory(PlatformTransactionManager transactionManager,
			DAOSource daoSource) {
		
		super(daoSource);

		if (transactionManager == null) {
			throw new IllegalArgumentException("Parameter transactionTemplate cannot be null");
		}

		this.transactionManager = transactionManager;
		this.daoSource = daoSource;

	}

	@Override
	@SuppressWarnings("unchecked")
	public <T> Controller<T, ?> build(Class<T> entityClass) {

		Controller<T, ?> controller = null;
		final DAO<T, Serializable> dao = daoSource.get(entityClass);

		if (dao != null) {

			TransactionTemplate template = new TransactionTemplate(transactionManager);
			template.afterPropertiesSet();

			final Controller<T, ?> delegate = super.build(entityClass);
			controller = new SpringControllerImpl(template, delegate);

		}

		return controller;

	}

	final private static class SpringControllerImpl<T, K extends Serializable> implements
			Controller<T, K> {

		final private Controller<T, K> controller;

		final private TransactionTemplate transactionTemplate;

		public SpringControllerImpl(TransactionTemplate transactionTemplate,
				Controller<T, K> controller) {

			if (controller == null) {
				throw new IllegalArgumentException("Parameter controller cannot be null");
			}

			if (transactionTemplate == null) {
				throw new IllegalArgumentException("Parameter transactionTemplate cannot be null");
			}

			this.controller = controller;
			this.transactionTemplate = transactionTemplate;

		}

		public int countAll() {
			return controller.countAll();
		}

		public void delete(final K id) {

			transactionTemplate.execute(new TransactionCallbackWithoutResult() {

				protected void doInTransactionWithoutResult(TransactionStatus status) {
					controller.delete(id);
				}
				
			});

		}

		public void delete(final T object) {
			
			transactionTemplate.execute(new TransactionCallbackWithoutResult() {

				protected void doInTransactionWithoutResult(TransactionStatus status) {
					controller.delete(object);
				}
				
			});
			
		}

		public void evict(final T object) {
			controller.evict(object);
		}

		public List<T> findAll() {
			return controller.findAll();
		}

		public List<T> findAll(final int firstResult, final int maxResults,
				final SortCriterion... sortConstraints) {
			return controller.findAll(firstResult, maxResults, sortConstraints);
		}

		public List<T> findByExample(final T example) {
			return controller.findByExample(example);
		}

		public T findById(final K id) {
			return controller.findById(id);
		}

		public List<T> findByIds(final K... ids) {
			return controller.findByIds(ids);
		}

		public boolean isPersistent(final T object) {
			return controller.isPersistent(object);
		}

		public T reattach(final T object) {
			return controller.reattach(object);
		}

		public void save(final T object) {
			
			transactionTemplate.execute(new TransactionCallbackWithoutResult() {

				protected void doInTransactionWithoutResult(TransactionStatus status) {
					controller.save(object);
				}
				
			});
			
		}

		@SuppressWarnings("unchecked")
		public T saveOrUpdate(final T object) {
			
			return (T) transactionTemplate.execute(new TransactionCallback() {

				public Object doInTransaction(TransactionStatus status) {
					return controller.saveOrUpdate(object);
				}
				
			});
			
		}

		@SuppressWarnings("unchecked")
		public T update(final T object) {
			
			return (T) transactionTemplate.execute(new TransactionCallback() {

				public Object doInTransaction(TransactionStatus status) {
					return controller.update(object);
				}
				
			});
			
		}

	}

}
